/**
 * Created by kenz on 2018/4/13.
 */

import {REQUEST_POSTS, RECEIVE_POSTS, INVALIDATE_SUBREDDIT, SELECT_SUBREDDIT} from '../constants'
import fetch from 'cross-fetch'

export function selectSubreddit(subreddit) {
  return {
    type: SELECT_SUBREDDIT,
    subreddit
  }
}

export const requestPosts = (subreddit) => {
  return {
    type: REQUEST_POSTS,
    subreddit
  }
}

export const receivePosts = (subreddit, json) => {
  return {
    type: RECEIVE_POSTS,
    subreddit,
    receivedAt: Date.now(),
    posts: json.data.children.map(child => child.data)
  }
}

export const invalidateSubreddit = subreddit => {
  return {
    type: INVALIDATE_SUBREDDIT,
    subreddit
  }
}

export const fetchPosts = subreddit => {
  return dispatch => {
    dispatch(requestPosts(subreddit))
    return fetch(`http://www.subreddit.com/r/${subreddit}.json`).then(
      response => response.json(),
      error => console.log('An error occurred.', error)
    ).then(json => dispatch(receivePosts(subreddit, json)))
  }
}